﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Json;
using Volo.Abp;
using Volo.Abp.Application.Dtos;

namespace TianShu.WebApi.Middlewares
{
    public class TianShuExceptionHandleMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;
        private readonly IWebHostEnvironment _env;

        public TianShuExceptionHandleMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, IWebHostEnvironment env)
        {
            _next = next;
            _env = env;
            _logger = loggerFactory.CreateLogger<TianShuExceptionHandleMiddleware>();
        }

        public async Task Invoke(HttpContext context)
        {

            try
            {
                await _next.Invoke(context);
            }
            catch (UserFriendlyException ufex)
            {
                ResultDto<bool> result = new ResultDto<bool>(ufex.Message);

                await context.Response.WriteAsJsonAsync(result);
                return;
            }
            catch (AbpException ufex)
            {
                ResultDto<bool> result = new ResultDto<bool>(ufex.Message);

                await context.Response.WriteAsJsonAsync(result);
                return;
            }
            catch (ArgumentException ufex)
            {
                ResultDto<bool> result = new ResultDto<bool>(ufex.Message);

                await context.Response.WriteAsJsonAsync(result);
                return;
            }
            catch (Exception ex)
            {
                if (_env.IsDevelopment())
                {
                    Console.WriteLine(ex);
                    await context.Response.WriteAsJsonAsync(ex);
                    return;
                }
                ResultDto<bool> result = new ResultDto<bool>("系统繁忙，请联系管理员");

                await context.Response.WriteAsJsonAsync(result);
                _logger.LogError(ex.ToString());
                return;
            }
        }
    }
}
